package com.wx.app.card.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.app.card.dao.entity.CardEntity;
import com.wx.app.card.dao.entity.MatchRecordEntity;
import com.wx.app.card.dao.entity.UserEntity;
import com.wx.app.card.dao.entity.UserImageEntity;
import com.wx.app.card.dao.mapper.CardMapper;
import com.wx.app.card.dao.mapper.MatchRecordMapper;
import com.wx.app.card.dao.mapper.UserImageMapper;
import com.wx.app.card.dao.mapper.UserMapper;
import com.wx.app.card.domain.ro.GetLevelCardRO;
import com.wx.app.card.domain.ro.UploadScoreRO;
import com.wx.app.card.domain.vo.GetLevelInfoVO;
import com.wx.app.card.utils.CacheUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 类功能描述：
 *
 * @author：刘富国
 * @createTime：2019/7/30 19:43
 */
@Api(tags = "A闯关模式")
@Slf4j
@RestController
public class MatchController extends BaseController {

    @Autowired
    private MatchRecordMapper matchRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserImageMapper userImageMapper;
    @Autowired
    private CardMapper cardMapper;


    @Value("${file.image.upload-url}")
    private String uploadUrl;


    /**
     * 上传分数
     */
    @ApiOperation(value = "上传分数")
    @PostMapping("/upload/score")
    public Object uploadScore(@RequestHeader String token, @RequestBody UploadScoreRO ro) {
        UserEntity user = userMapper.selectById(CacheUtils.getUserId(token));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        MatchRecordEntity entity = new MatchRecordEntity();
        entity.setCreateTime(new Date());
        entity.setScore(Long.valueOf(ro.getScore()));
        entity.setUserId(CacheUtils.getUserId(token));
        matchRecordMapper.insert(entity);
        if (ro.getScore() > user.getMaxScore()) {
            user.setMaxScore(ro.getScore());
            userMapper.updateById(user);
        }
        return success();
    }

    /**
     * 图片上传
     */
    @ApiOperation(value = "上传图片")
    @ResponseBody
    @PostMapping("upload/image")
    public Object upload(@RequestHeader String token, HttpServletRequest request,
                         @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return fail("没有找到相对应的文件");
        }
        String fileName = file.getOriginalFilename();
        String path;
        String type;
        type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1) : null;
        if (type == null) {
            return fail("文件类型为空");

        }
        List<String> typeList = Arrays.asList("GIF", "PNG", "JPG", "BMP", "JPEG");
        if (!typeList.contains(type.toUpperCase())) {
            return fail("请选择正确格式的图片重新上传");
        }
        // 自定义的文件名称
        String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
        // 设置存放图片文件的路径
        path = uploadUrl + trueFileName;
        file.transferTo(new File(path));
        //上传数据库
        UserImageEntity entity = new UserImageEntity();
        entity.setCreateTime(new Date());
        entity.setImgUrl(path);
        entity.setUserId(CacheUtils.getUserId(token));
        userImageMapper.insert(entity);
        return success();
    }


    /**
     * 关卡卡片
     */
    @ApiOperation(value = "获取关卡卡片")
    @PostMapping("/card/list")
    public Object levelCard(@RequestHeader String token, @RequestBody GetLevelCardRO ro) {
        List<GetLevelInfoVO> voList = new ArrayList<>();

        List<CardEntity> levels = new ArrayList<>();
        List<String> yearList = Arrays.asList("1970", "1980", "1990", "2000", "2010");
        for (int i = 0; i < 4; i++) {
            int num = RandomUtil.randomInt(0, 5);
            levels.add(cardMapper.selectOne(new QueryWrapper<CardEntity>()
                    .eq("year", yearList.get(num))
                    .last("order by rand() limit 1")));
            levels.add(cardMapper.selectOne(new QueryWrapper<CardEntity>()
                    .eq("year", yearList.get(num))
                    .last("order by rand() limit 1")));
        }

        for (int i = 0; i < levels.size(); i++) {
            CardEntity cardEntity = levels.get(i);
            GetLevelInfoVO vo = new GetLevelInfoVO();
            vo.setId(cardEntity.getId());
            vo.setMiniImgUrl(cardEntity.getMiniImgUrl());
            vo.setYearImgUrl(cardEntity.getYearImgUrl());
            vo.setYear(cardEntity.getYear());
            voList.add(vo);
        }
        Collections.shuffle(voList);
        return success(voList);
    }

}
